package com.wsd.dao.impl;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wsd.bean.Category;
import com.wsd.bean.Price;
import com.wsd.bean.Products;
import com.wsd.dao.ProductsDaoInterface;
import com.wsd.util.WebApplicationContextUtils;

/**
 * A data access object (DAO) providing persistence and search support for
 * Products entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.wsd.bean.Products
 * @author MyEclipse Persistence Tools
 */

public class ProductsDAO extends HibernateDaoSupport implements ProductsDaoInterface{
	private static final Log log = LogFactory.getLog(ProductsDAO.class);

	protected void initDao() {
		// do nothing
	}

	public void save(Products transientInstance) {
		log.debug("saving Products instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Products persistentInstance) {
		log.debug("deleting Products instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			re.printStackTrace();
			throw re;
		}
	}

	public Products findById(java.lang.Integer id) {
		log.debug("getting Products instance with id: " + id);
		try {
			Products instance = (Products) getHibernateTemplate().get(
					"com.wsd.bean.Products", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	@SuppressWarnings("unchecked")
	public List<Products> findAll() {
		log.debug("finding all Products instances");
		try {
			String queryString = "from Products p order by p.PId desc";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	@SuppressWarnings("unchecked")
	public List findByExample(Object exampleEntity) {
		log.debug("finding by Products instances");
		try {
			return getHibernateTemplate().findByExample(exampleEntity);
		} catch (RuntimeException re) {
			log.error("find example failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Products> findOnePage(int start, int pageSize) {
		log.debug("get onepage Products list");
		String queryString = "from Products p order by p.PId desc";
		try {
			Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString);
			query.setFirstResult(start);
			query.setMaxResults(pageSize);
			return query.list();
		} catch (RuntimeException re) {
			log.error("get onepage Products list fail", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List getTotallines() {
		log.debug("get Products totallines");
		String queryString = "select count(*) from Products";
		try {
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("get Products totallines fail", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List getTotallines(String keyWord) {
		log.debug("get Products totallines");
		String queryString = "select count(*) from Products p where p.model like ? or p.barcode like ? or p.PName like ? or p.factory like ? or p.category.CName like ?";
		try {
			Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString);
			query.setString(0, "%" + keyWord + "%");
			query.setString(1, "%" + keyWord + "%");
			query.setString(2, "%" + keyWord + "%");
			query.setString(3, "%" + keyWord + "%");
			query.setString(4, "%" + keyWord + "%");
			return query.list();
		} catch (RuntimeException re) {
			log.error("get Products totallines fail", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Products> searchProducts(int start, int pageSize, String keyWord) {
		log.debug("search products by keyword");
		try {
			String queryString = "from Products p where p.model like ? or p.barcode like ? or p.PName like ? or p.factory like ? or p.category.CName like ? order by p.PId desc";
			Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString);
			query.setString(0, "%" + keyWord + "%");
			query.setString(1, "%" + keyWord + "%");
			query.setString(2, "%" + keyWord + "%");
			query.setString(3, "%" + keyWord + "%");
			query.setString(4, "%" + keyWord + "%");
			query.setFirstResult(start);
			query.setMaxResults(pageSize);
			
			return query.list();
		} catch (RuntimeException re) {
			log.error("search products by keyword fail", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List getTotallines(int cid) {
		log.debug("getTotallines by keyword");
		CategoryDAO categoryDAO = (CategoryDAO) WebApplicationContextUtils.getBean("categoryDAO");
		Category category = categoryDAO.findById(cid);
		try {
			String sql = "select count(*) from Products p where p.category.lft >= :lft and p.category.rgt <=:rgt";
			//Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString);
			Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
			query.setInteger("lft", category.getLft());
			query.setInteger("rgt", category.getRgt());
			return query.list();
		} catch (RuntimeException re) {
			log.error("getTotallines by keyword fail", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Products> categoryProducts(int start, int pageSize, int cid) {
		log.debug("search products by category");
		CategoryDAO categoryDAO = (CategoryDAO) WebApplicationContextUtils.getBean("categoryDAO");
		Category category = categoryDAO.findById(cid);
		try {
			String sql = "from Products p where p.category.lft >= :lft and p.category.rgt <= :rgt order by p.PId desc";
			Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
			query.setInteger("lft", category.getLft());
			query.setInteger("rgt", category.getRgt());
			query.setFirstResult(start);
			query.setMaxResults(pageSize);
			return query.list();
		} catch (RuntimeException re) {
			log.error("search products by category fail", re);
			throw re;
		}
	}
	
	public List<Products> rankByModel(short model, int num){
		log.debug("rank products by model");
		try {
			String queryString = "select * from products p, product_rank pr where pr.p_id = p.p_id and pr.b_model = ? order by pr.b_id";
			Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString).addEntity(Products.class);
			query.setInteger(0, model);
			query.setMaxResults(num);
			return query.list();
		} catch (RuntimeException re) {
			log.error("rank products by model fail", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.ProductsDaoInterface#update(com.wsd.bean.Products)
	 */
	public void update(Products products) {
		getHibernateTemplate().update(products);
	}

	/* (non-Javadoc)
	 * @see com.wsd.dao.ProductsDaoInterface#deletePrice(com.wsd.bean.Products)
	 */
	public void deletePrice(Products preProduct) {
		for (Iterator iter = preProduct.getPrices().iterator(); iter.hasNext();) {
			Price price = (Price) iter.next();
			getHibernateTemplate().delete(price);
		}
	}


}